package org.example.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liyishan
 * @date 2024/5/22 11:31
 * @apiNote
 */

public class Test00637AverageOfLevels {

    public List<Double> averageOfLevels(TreeNode root) {
        List<Integer> counts = new ArrayList<Integer>();
        List<Double> sums = new ArrayList<Double>();
        dfs(root, 0, counts, sums);
        List<Double> averages = new ArrayList<Double>();
        int size = sums.size();
        for (int i = 0; i < size; i++) {
            averages.add(sums.get(i) / counts.get(i));
        }
        return averages;
    }

    public void dfs(TreeNode root, int level, List<Integer> counts,List<Double> sums){
        if(root == null){
            return;
        }
        if (level < sums.size()) {
            sums.set(level, sums.get(level) + root.val);
            counts.set(level, counts.get(level) + 1);
        } else {
            sums.add(1.0 * root.val);
            counts.add(1);
        }
        dfs(root.left,level+1,counts,sums);
        dfs(root.right,level+1,counts,sums);
    }
}
